package com.guaji.system.deepseek

import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.format.DateFormat
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.guaji.system.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.net.SocketTimeoutException
import java.util.Date
import java.util.concurrent.TimeUnit

class DeepseekMainActivity : AppCompatActivity() {

    // DeepSeek API配置
    private val API_KEY = "sk-f6666b909cbe47079d4521a4282e8a23" // 替换为实际API密钥
    private val API_URL = "https://api.deepseek.com/v1/chat/completions"
    private val client = OkHttpClient.Builder()
        .connectTimeout(60, TimeUnit.SECONDS)
        .readTimeout(120, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build()
    private val JSON = "application/json; charset=utf-8".toMediaType()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_deepseek_main)

        // 处理窗口Insets
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 发送按钮点击事件
        findViewById<Button>(R.id.button).setOnClickListener {
            val questionEditText = findViewById<EditText>(R.id.question)
            val question = questionEditText.text.toString().trim()
            if (question.isNotEmpty()) {
                // 1. 立即显示用户问题（实时更新UI）
                appendMessage("你", question)
                questionEditText.text.clear()
                // 2. 发送请求并实时更新状态
                sendQuestionToDeepSeek(question)
            } else {
                Toast.makeText(this, "请输入问题", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun sendQuestionToDeepSeek(question: String) {
        // 3. 先在主线程显示"思考中"，不等待网络请求（关键：实时反馈）
        val thinkingMessageId = System.currentTimeMillis() // 用ID标记这条"思考中"消息
        appendMessage("DeepSeek", "思考中...", thinkingMessageId)

        // 4. 在IO线程执行网络请求，不阻塞UI
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 构建请求体
                val requestBody = buildRequestBody(question)
                // 发送请求并获取响应
                val response = postAsync(API_URL, requestBody, mapOf("Authorization" to "Bearer $API_KEY"))
                // 解析响应
                val answer = parseResponse(response)

                // 5. 回到主线程，替换"思考中"为实际回答（实时更新）
                withContext(Dispatchers.Main) {
                    replaceThinkingMessage(thinkingMessageId, "DeepSeek", answer)
                }
            } catch (e: Exception) {
                // 6. 错误时也回到主线程更新UI
                val errorMsg = when (e) {
                    is SocketTimeoutException -> "请求超时，请检查网络"
                    is IOException -> "网络错误: ${e.message}"
                    else -> "错误: ${e.message}"
                }
                withContext(Dispatchers.Main) {
                    replaceThinkingMessage(thinkingMessageId, "系统", errorMsg)
                }
            }
        }
    }

    // 新增：替换"思考中"消息为实际内容
    private fun replaceThinkingMessage(thinkingMessageId: Long, sender: String, newMessage: String) {
        val chatView = findViewById<TextView>(R.id.chat_view)
        val currentText = chatView.text.toString()
        // 找到"思考中"消息的位置（通过时间戳+ID辅助定位）
        val thinkingMarker = "\n\n[DeepSeek] ${DateFormat.format("HH:mm:ss", thinkingMessageId)}"
        val thinkingStartIndex = currentText.indexOf(thinkingMarker)

        if (thinkingStartIndex != -1) {
            // 计算"思考中"消息的结束位置
            val thinkingEndIndex = currentText.indexOf("\n\n", thinkingStartIndex + 1).takeIf { it != -1 }
                ?: currentText.length
            // 构建新消息
            val timeStamp = DateFormat.format("HH:mm:ss", Date()).toString()
            val newContent = SpannableStringBuilder().apply {
                append("\n\n[$sender] $timeStamp\n")
                append("-------------------\n")
                append(newMessage)
            }.toString()
            // 替换旧消息为新消息（实时更新UI）
            chatView.text = currentText.replaceRange(thinkingStartIndex, thinkingEndIndex, newContent)
        } else {
            // 如果没找到，直接追加（兼容边界情况）
            appendMessage(sender, newMessage)
        }
        // 滚动到底部
        chatView.post { chatView.scrollTo(0, chatView.bottom) }
    }

    // 格式化并添加消息到聊天区域（支持标记"思考中"消息）
    private fun appendMessage(sender: String, message: String, messageId: Long = 0) {
        val chatView = findViewById<TextView>(R.id.chat_view)
        // 用当前时间戳作为消息时间，确保唯一性
        val timeStamp = DateFormat.format("HH:mm:ss", if (messageId == 0L) Date() else Date(messageId)).toString()

        // 构建格式化的消息
        val formattedMessage = SpannableStringBuilder().apply {
            append("\n\n[$sender] $timeStamp\n")
            append("-------------------\n")
            append(message)
        }

        // 在主线程更新UI（确保实时性）
        chatView.post {
            chatView.append(formattedMessage)
            chatView.scrollTo(0, chatView.bottom) // 立即滚动到底部
        }
    }

    // 构建请求体
    private fun buildRequestBody(question: String): String {
        val requestBody = JSONObject()
        requestBody.put("model", "deepseek-chat")

        val messages = JSONArray()
        messages.put(JSONObject().apply {
            put("role", "system")
            put("content", "You are a helpful assistant")
        })
        messages.put(JSONObject().apply {
            put("role", "user")
            put("content", question)
        })

        requestBody.put("messages", messages)
        requestBody.put("temperature", 0.7)
        return requestBody.toString()
    }

    // 解析响应
    private fun parseResponse(response: String): String {
        try {
            val jsonResponse = JSONObject(response)
            val choices = jsonResponse.getJSONArray("choices")
            if (choices.length() > 0) {
                return choices.getJSONObject(0).getJSONObject("message").getString("content")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return "无法解析响应: $response"
    }

    // 异步发送POST请求
    suspend fun postAsync(
        url: String,
        json: String,
        headers: Map<String, String> = emptyMap()
    ): String = withContext(Dispatchers.IO) {
        val requestBody = json.toRequestBody(JSON)
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .apply { headers.forEach { (key, value) -> addHeader(key, value) } }
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("请求失败: ${response.code}")
            response.body?.string() ?: ""
        }
    }
}